<template>
  <div class="app-container">
    <div v-show="!state.showDetails && !showModify.visible">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-button>
          <el-button
            v-if="$permission('license:delete')"
            :disabled="!tableInfo.selections.length"
            style="margin-right: 10px"
            @click="deleteData()"
            >删除</el-button
          >
          <el-button
            v-if="$permission('license:enabled')"
            :disabled="
              !tableInfo.selections.length ||
              !!tableInfo.selections.filter((item) => item.status === 1).length
            "
            style="margin-right: 10px"
            @click="batchEnableLicenses('enabled')"
            >启用</el-button
          >
          <el-button
            v-if="$permission('license:enabled')"
            :disabled="
              !tableInfo.selections.length ||
              !!tableInfo.selections.filter((item) => item.status === 0).length
            "
            @click="batchDisableLicenses('disabled')"
            >停用</el-button
          >
          <el-button
            v-if="$permission('license:upload')"
            style="marginleft: 10px"
            @click="uploadImg"
            >上传图片</el-button
          >
        </template>
        <template v-slot:filter-uploadFile>
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="importProduct"
            :before-upload="beforeProductUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入模板</el-button>
          </el-upload>
        </template>
      </page-filter>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getLicensePage"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-licenseNumber="scope">
          <span class="slip-edit" @click="showLicenseDetail(scope.row.id)">{{
            scope.row.licenseNumber
          }}</span>
        </template>
        <template v-slot:col-licenseApplicationType="scope">
          <span v-if="[1,2].includes(scope.row.licenseApplicationType)">{{ scope.row.licenseApplicationType == 1 ? '耗材' : '设备' }}</span>
          <span v-else>-</span>
        </template>
      </table-container>
    </div>
    <modify
      v-if="showModify.visible"
      :id="state.id"
      :licenseId="showModify.licenseId"
      v-model:visible="showModify.visible"
      :title="showModify.title"
      :type="showModify.type"
      @returnModify="returnModify"
    ></modify>
    <licenseDetails
      v-if="state.showDetails"
      v-model:visible="state.showDetails"
      :id="state.id"
      @returnBack="getList"
    ></licenseDetails>
    <DialogUpload
      v-if="dialogUploadInfo.visible"
      v-model:show-dialog="dialogUploadInfo.visible"
      :vaildate-api="dialogUploadInfo.vaildateApi"
      :api="dialogUploadInfo.api"
      :rulesText="'上传规则：以证号作为图片名称，同一证号上传多张图片，用证号+@#1，证号+@#2，同一证照编码数字依次叠加\n例：证号a.png，证号a@#1.png，证号a@#2.png\n\xa0\xa0\xa0\xa0\xa0\xa0\xa0证号b.png，证号b@#1.png，证号b@#2.png'"
      @callback="getList"
    >
    </DialogUpload>
  </div>
</template>

<script setup name="license">
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import DialogUpload from '@/components/DialogUpload/index'
import {
  getLicensePage,
  batchDeleteLicense,
  licensesVaildateFile,
  licensesFile,
  downloadFileLicenses,
} from '@/api/core.js'
import axios from 'axios'
import licenseDetails from './details'
import { disableLicenses, enableLicenses } from '../../../api/core'
import { exportTemplateExcel } from '@/api/pub'
import { ElLoading, ElMessage } from 'element-plus'
import modify from './modify'

const { proxy } = getCurrentInstance()
const state = reactive({
  id: '',
  showDetails: false,
  action: axios.defaults.baseURL + '/pub/uploadfile',
})
const dialogUploadInfo = reactive({
  visible: false,
  api: licensesFile,
  vaildateApi: licensesVaildateFile,
})
const uploadInfo = reactive({
  action: axios.defaults.baseURL + '/core/licenses/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})

// 相关列表
const listTypeInfo = reactive({
  brandList: [],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    nameLike: '',
    sort: 'create_time desc',
    searchType: 'license',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('license:add'),
    },
    { type: 'slot', value: 'button' },
    {
      type: 'button',
      label: '下载图片',
      event: downloadFile,
      show: proxy.$permission('license:downloadFile'),
    },

    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    { type: 'slot', value: 'uploadFile' },
    {
      type: 'input',
      label: '名称/证号',
      value: 'keyword',
      event: search,
    },
    {
      type: 'select-model',
      label: '状态',
      value: 'status',
      code: 'enabled_type',
      event: search,
    },
    {
      type: 'select-model',
      label: '证照分类',
      value: 'licenseApplicationType',
      code: 'license_application_type',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  selections: [],
  data: [],
  fieldList: [
    { label: '证号', value: 'licenseNumber', type: 'slot' },
    { label: '证照类型', value: 'licenseTypeValue' },
    { label: '证照分类', value: 'licenseApplicationType',type: 'slot' },
    { label: '产品名称', value: 'licenseName' },
    { label: '生效日期', value: 'licenseBeginDate' },
    { label: '失效日期', value: 'licenseEndDate' },
    { label: '厂家名称', value: 'brandName' },
    { label: '状态', value: 'statusValue' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('license:update'),
      },
      {
        label: '删除',
        event: deleteData,
        show: proxy.$permission('license:delete'),
      },
      {
        label: proxy.$t('enabled'),
        event: enabled,
        show: proxy.$permission('license:enabled'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: proxy.$t('disabled'),
        event: disabled,
        show: proxy.$permission('license:enabled'),
        ifRender(row) {
          return row.status === 1
        },
      },
    ],
  },
})
// 表单相关
const formInfo = reactive({
  ref: null,
  data: {
    licenseType: 'record_no',
  },
  fieldList: [
    {
      label: '证照类型',
      value: 'licenseType',
      type: 'select-model',
      code: 'license_type',
    },
    {
      label: '管理类别',
      value: 'manageType',
      type: 'select-model',
      show: true,
      code: 'license_manage_type',
    },
    { label: '证号', value: 'licenseNumber', type: 'input' },
    { label: '产品名称', value: 'licenseName', type: 'input' },
    { label: '英文名称', value: 'enName', type: 'input' },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'date',
      dateType: 'date',
    },
    { label: '证照失效日期', value: 'licenseEndDate', type: 'date' },
    {
      label: '生产厂家',
      value: 'brand',
      type: 'select',
      list: 'brandList',
      filterable: true,
    },
    { label: '包装规格', value: 'packedStandard', type: 'input' },
    {
      label: '产品有效期',
      value: 'validity',
      type: 'number',
      max: 30000,
    },
    {
      label: '有效期单位',
      value: 'validityUnit',
      type: 'select-model',
      code: 'validity_unit',
    },
    { label: '生产地址', value: 'productionAddress', type: 'input' },
    { label: '预计用途', value: 'expectedUse', type: 'input' },
    { label: '存储条件', value: 'storageCondition', type: 'input' },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '证照',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  recordRules: {
    //备案证
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],
    packedStandard: [
      { required: true, message: '请输入规格', trigger: 'blur' },
    ],
  },
  regcRules: {
    //注册证
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],
    packedStandard: [
      { required: true, message: '请输入规格', trigger: 'blur' },
    ],
    licenseEndDate: [
      { required: true, message: '请选择证照失效日期', trigger: 'change' },
    ],
  },
  otherRules: {
    //非医疗耗材
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],
    packedStandard: [
      { required: true, message: '请输入规格', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})

const showModify = reactive({
  title: '',
  licenseId:'',
  type: 'creat',
  visible: false,
})

watch(
  () => proxy.$route,
  (route) => {
    const params = route.params
    if (params && params.id && route.name === 'license') {
      state.id = params.id
      showModify.visible = false
      state.showDetails = true
    }
  },
  {
    immediate: true,
  }
)

onMounted(() => {
  getList()
})
function downloadFile() {
  downloadFileLicenses(filterInfo.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}

function uploadImg() {
  dialogUploadInfo.visible = true
}
function returnModify() {
  if (state.id) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function create() {
  showModify.type = 'create'
  showModify.title = '新增'
  showModify.licenseId = ''
  state.id = ''
  showModify.visible = true
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  showModify.title = '修改'
  showModify.licenseId = row.licenseId
  showModify.type = 'update'
  state.id = row.id
  showModify.visible = true
}
function downloadTemplate() {
  exportTemplateExcel('license_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function search() {
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function enabled(row) {
  const ids = getIds(row)
  enableLicenses(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disabled(row) {
  const ids = getIds(row)
  disableLicenses(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function getIds(row) {
  if (row) {
    return [row.id]
  } else {
    return tableInfo.selections.map((value) => value.id)
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function batchDisableLicenses(status, row) {
  const ids = getIds(row)
  disableLicenses(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function batchEnableLicenses(status, row) {
  const ids = getIds(row)
  enableLicenses(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function showLicenseDetail(id) {
  sessionStorage.setItem('storeRowId', id)
  state.id = id
  state.showDetails = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function deleteData(row) {
  const ids = getIds(row)
  console.log(ids)
  if (!ids || ids.length === 0) {
    proxy.$message({
      type: 'warning',
      message: '请选择要删除的数据',
      showClose: true,
    })
  } else {
    batchDeleteLicense(ids).then((res) => {
      if (res) {
        getList()
      }
    })
  }
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
</script>

<style scoped></style>
